import lodash from 'lodash';
import * as data from './data';
import log from '../../../log';
import * as util from '../../../util';
import * as userCore from '../user/core';
import * as userData from '../user/data';
import {UserType, password} from '../../dict';

const likeParms = 'name'.split(',');

/*export function getPids(id) {
    return data.find([{id}], 0).then(res => {
        log.info('getAllInstitutionIs result----', util.data(res));
        let pids = [];
        res = res.toJSON() || [];
        if (res.length > 0) {
            res = res[0];
            if (res.pid) {
                pids.push(res.pid);
                return getPids(res.pid).then(r => {
                    pids = [...pids, ...r];
                    return pids;
                });
            }
        }
        return pids;
    });
}*/
/**
 * 查询上级所有层级的机构id集合
 */
export function getPids(nodes = [], sid, pid = null, enable) {
    const children = [];
    for (const i in nodes) {
        const node = nodes[i];
        let status = true;
        if (enable) {
            status = node.status === '1';
        }
        if (node.id === sid && status) {
            const sons = getPids(nodes, node.pid, pid, enable);
            if (sons.length > 0) {
                children.push(node.id, ...sons);
            } else {
                children.push(node.id);
            }
        }
    }
    return children;
}

/**
 * 获取本机构和所有层级父级机构id集合
 * @param id 机构id
 * @returns {Array}
 */
export function getAllLevelPids(id) {
    return data.findNoWithRelated().then(res => {
        res = res.toJSON() || [];
        const r = getPids(res, id, null, false);
        const ret = lodash.uniq([id, ...r]);
        log.info('getAllLevelPids result:', ret);
        return ret;
    });
}

/**
 * 查询下级所有层级的机构id集合
 */
export function getSids(nodes = [], sid, pid = null, enable) {
    const children = [];
    for (const i in nodes) {
        const node = nodes[i];
        let status = true;
        if (enable) {
            status = node.status === '1';
        }
        if (((!pid && !node.pid) || node.pid === pid) && node.id !== sid && status) {
            const sons = getSids(nodes, sid, node.id, enable);
            if (sons.length > 0) {
                children.push(node.id, ...sons);
            } else {
                children.push(node.id);
            }
        }
    }
    return children;
}

/**
 * 获取本机构和所有层级下级机构id集合
 * @param id 机构id
 * @returns {Array}
 */
export function getAllLevelSonIds(id) {
    return data.findNoWithRelated().then(res => {
        res = res.toJSON() || [];
        const r = getSids(res, null, id, false);
        const ret = lodash.uniq([id, ...r]);
        log.info('getAllLevelSonIds result:', ret);
        return ret;
    });
}

/**
 * 查询下级所有层级的机构id，name对象集合
 */
function getSonObjs(nodes = [], sid, pid = null, enable) {
    const children = [];
    for (const i in nodes) {
        const node = nodes[i];
        let status = true;
        if (enable) {
            status = node.status === '1';
        }
        if (((!pid && !node.pid) || node.pid === pid) && node.id !== sid && status) {
            const sons = getSids(nodes, sid, node.id, enable);
            if (sons.length > 0) {
                children.push({id: node.id, name: node.name}, ...sons);
            } else {
                children.push({id: node.id, name: node.name});
            }
        }
    }
    return children;
}

/**
 * 查询下级所有层级的机构id，name对象集合
 * @param id 机构id
 * @returns {Array}
 */
export function getAllLevelSonObjs(id) {
    return data.findNoWithRelated().then(res => {
        res = res.toJSON() || [];
        const my = lodash.find(res, {id});
        const r = getSonObjs(res, null, id, false);
        const ret = lodash.uniq([{id: my.id, name: my.name}, ...r]);
        log.info('getAllLevelSonObjs result:', ret);
        return ret;
    });
}

export function fetch(query, page, pageSize) {
    return util.resolve().then(() => {
        log.info('fetch institution params----', query);
        const pageOpt = {
            page,
            pageSize
        };
        let where = [];
        if (lodash.keys(query).length > 0) {
            lodash.mapKeys(query, (value, key) => {
                if (likeParms.indexOf(key) >= 0) {
                    where.push([`${key}`, 'like', `%${value}%`]);
                } else {
                    where.push([`${key}`, '=', `${value}`]);
                }
            });
        }
        /*const {pid = ''} = query;
        where.push(['pid', '=', pid]);*/
        if (where.length < 1) {
            where = null;
        }
        return data.fetch(where, 1, pageOpt).then(res => {
            log.info('fetch institution result----', res.toJSON());
            return util.data(res, 1);
        });
    }).catch(err => {
        log.error('fetch institution is err----', err);
        return err;
    });
}
export function find(query) {
    return util.resolve().then(() => {
        log.info('find institution params----', query);
        let where = [];
        if (lodash.keys(query).length > 0) {
            lodash.mapKeys(query, (value, key) => {
                if (likeParms.indexOf(key) >= 0) {
                    where.push([`${key}`, 'like', `%${value}%`]);
                } else if (key === 'ids') {
                    where.push(['id', 'in', `${value}`]);
                } else {
                    where.push([`${key}`, '=', `${value}`]);
                }
            });
        }
        /*const {pid = '', id} = query;
        if (!id) {
            where.push(['pid', '=', pid]);
        }*/
        if (where.length < 1) {
            where = null;
        }
        return data.find(where, 1).then(res => {
            //log.info('find institution result----', util.data(res));
            return util.data(res);
        });
    }).catch(err => {
        log.error('find institution is err----', err);
        return err;
    });
}
export function add(institution) {
    return util.resolve().then(() => {
        log.info('add institution params----', institution);
        return data.find([{name: institution.name}], 0).then(res => {
            if (res.toJSON().length > 0) {
                throw '机构名称重复！';
            }
            //添加机构管理员：用户名adminUser
            const {adminUser} = lodash.cloneDeep(institution);
            if (!adminUser) {
                throw '机构管理员用户名没有设置';
            }
            delete institution.adminUser;
            institution.id = util.uuid();
            institution.status = '1';
            const userInfo = {
                id: util.uuid(),
                username: adminUser,
                userType: UserType.institutionManager,
                password: password.institution,
                institutionId: institution.id,
                status: '1',
            };
            return userCore.getAddInfo(userInfo).then(user => {
                log.info('add institution adminUser ----', JSON.stringify(user));
                institution.adminUserId = user.id;
                return data.add(institution, user).then(r => {
                    log.info('add institution result----', r);
                    return institution;
                });
            });
        });
    }).catch(err => {
        log.error('add institution is err----', err);
        return err;
    });
}
export function edit(institution) {
    return util.resolve().then(() => {
        log.info('edit institution params----', institution);
        return data.find([['id', '<>', `${institution.id}`], ['name', '=', `${institution.name}`]], 1).then(res => {
            if (res.toJSON().length > 0) {
                throw '机构名称重复！';
            }
            //判断机构管理员用户名是否修改，是否重复
            let user = null;
            if (institution.adminUserName && institution.adminUserId) {
                return userData.getUser({id: institution.adminUserId}).then(r => {
                    r = r.toJSON() || [];
                    r = r[0];
                    if (r) {
                        if (!r.username || r.username !== institution.adminUserName) {
                            //判断用户名是否重复
                            return userData.getUser([['id', '<>', institution.adminUserId], ['username', '=', institution.adminUserName]]).then(r1 => {
                                r1 = r1.toJSON() || [];
                                if (r1.length === 0) {
                                    user = {
                                        id: institution.adminUserId,
                                        username: institution.adminUserName
                                    };
                                    return data.edit(institution, user).then(res => {
                                        log.info('edit institution result----', util.data(res));
                                        return util.data(res);
                                    });
                                }
                                return data.edit(institution, user).then(res => {
                                    log.info('edit institution result----', util.data(res));
                                    return util.data(res);
                                });
                            });
                        }
                    }
                    return data.edit(institution, user).then(res => {
                        log.info('edit institution result----', util.data(res));
                        return util.data(res);
                    });
                });
            }
            return data.edit(institution, user).then(res => {
                log.info('edit institution result----', util.data(res));
                return util.data(res);
            });
        });
    }).catch(err => {
        log.error('edit institution is err----', err);
        return err;
    });
}
export function del(id) {
    return util.resolve().then(() => {
        log.info('delete institution params----', id);
        return data.del(id).then(res => {
            log.info('delete institution result----success', util.data(res));
            return util.data(res);
        });
    }).catch(err => {
        log.error('delete institution is err----', err);
        return err;
    });
}

export function getAllLevelSonObjsByQuery(query) {
    const id = query.id;
    delete query.id;
    return data.findNoWithRelated().then(res => {
        res = res.toJSON() || [];
        if (id && id.length > 0) {
            const r = getSids(res, null, id, false);
            query.ids = lodash.uniq([id, ...r]);
        }

        return util.resolve().then(() => {
            log.info('find institution params----', query);
            let where = [];
            if (lodash.keys(query).length > 0) {
                lodash.mapKeys(query, (value, key) => {
                    if (likeParms.indexOf(key) >= 0) {
                        where.push([`${key}`, 'like', `%${value}%`]);
                    } else if (key === 'ids') {
                        where.push(['id', 'in', value]);
                    } else {
                        where.push([`${key}`, '=', `${value}`]);
                    }
                });
            }
            if (where.length < 1) {
                where = null;
            }
            return data.findNoWithRelated(where, 1).then(res => {
                return util.data(res);
            });
        }).catch(err => {
            log.error('find institution is err----', err);
            return err;
        });
    });
}

